package com.seeyon.apps.ext.cop.button.demo;

import com.seeyon.ctp.common.AppContext;
import com.seeyon.ctp.organization.bo.OrganizationMessage;
import com.seeyon.ctp.organization.dao.OrgHelper;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.aspectj.lang.ProceedingJoinPoint;
import snail.common.utils.DateHelper;
import snail.common.utils.JSONHelper;
import snail.common.utils.MapHelper;
import snail.common.utils.db.DBHelper;
import snail.common.utils.db.DataSourceHelper;
import snail.common.web.HTTPHelper;

import javax.sql.DataSource;
import java.io.File;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class SynDept {

    private static final Log logger = LogFactory.getLog(SynDept.class);

    String url = "http://10.37.129.2:8989/selectDept";


    //正式数据源
    private static String urls = "jdbc:mysql://10.211.55.2:3306/cop?serverTimezone=UTC&useUnicode=true&characterEncoding=utf-8";// 连接URL字符串
    private static String user = "root";// 数据库用户名
    private static String password = "Mysql123456";// 用户密码

    /**
     * 查找用户登陆名
     * @param id
     * @return
     */
    public String selectDepRoleCop(String id) {

        // 登录认证逻辑，用户名和密码正确时返回true即可
        DataSource ds = DataSourceHelper.getMySQL6XDatasource(urls, user, password);
        DBHelper dbhelper = DBHelper.getInstance(ds);
        try {
            String userList = dbhelper.queryString("select b.login_name from ORG_MEMBER a left join " +
                    "ORG_PRINCIPAL b on  a.id = b.MEMBER_ID where a.id = ?", id);
            return userList;
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
        return "";
    }

    public Object myAround(ProceedingJoinPoint pjp) throws Throwable {

        HTTPHelper.isDebug();
        // 设置日志文件
        HTTPHelper.setLogFile(new File(AppContext.getCfgHome(),("../../../../logs/snail.httphelper.4801_UpdateDept." + DateHelper.getCurrentDate("yyyy-MM-dd") + ".log")));
        // HTTP请求（get,post,put,delete等）
        System.out.println(pjp.getArgs()[1]);


        Map<String, Object>  ect = (Map<String, Object>)  pjp.getArgs()[1];


        String parentDeptId = String.valueOf(ect.get("superDepartment"));

        String depManager = String.valueOf(ect.get("deptrole0"));
        String depLeader = String.valueOf(ect.get("deptrole1"));
        String assistant = String.valueOf(ect.get("deptrole5"));

        List managerList = new ArrayList();

        List leaderList = new ArrayList();

        List assistantList = new ArrayList();

        if (depManager != null && depManager.contains("|")) {
            if (depManager.contains(",")) {
                String[] depManagers = depManager.split(",");
                for (int i = 0; i<depManagers.length; i++){
                    String deptManger = depManagers[i].split("\\|")[1];
                    managerList.add(selectDepRoleCop(deptManger));
                }
            }else {
                String deptManger = depManager.split("\\|")[1];
                managerList.add(selectDepRoleCop(deptManger));
            }

        }

        if (depLeader != null && depLeader.contains("|")) {
            if (depLeader.contains(",")) {
                String[] depLeaders = depLeader.split(",");
                for (int i = 0; i<depLeaders.length; i++){
                    String deptLeader = depLeaders[i].split("\\|")[1];
                    leaderList.add(selectDepRoleCop(deptLeader));
                }
            }else {
                String deptLeader = depLeader.split("\\|")[1];
                leaderList.add(selectDepRoleCop(deptLeader));
            }

        }
        /**
         * 判断助理是否为空，如果含｜在判断逗号区分在合并
         */
        if (assistant != null && assistant.contains("|")) {
            if (assistant.contains(",")) {
                String[] assistants = assistant.split(",");
                for (int i = 0; i<assistants.length; i++){
                    String deptAssistant = assistants[i].split("\\|")[1];
                    assistantList.add(selectDepRoleCop(deptAssistant));
                }
            }else {
                String deptAssistant = assistant.split("\\|")[1];
                assistantList.add(selectDepRoleCop(deptAssistant));
            }

        }



        if (parentDeptId != null && parentDeptId.contains("|")) {
            parentDeptId = parentDeptId.split("\\|")[1];
        } else {
            parentDeptId = String.valueOf(pjp.getArgs()[0]);
        }


        String body = MapHelper.builder("deptId", ect.get("id"))
                .put("deptName", ect.get("name"))
                .put("superiorId", parentDeptId)
                .put("depManagers", managerList)
                .put("depLeader", leaderList)
                .put("assistant", assistantList)
                .toJson();
        try {
            Map<String, Object> header = MapHelper.builder("Content-Type", "application/json").body();

            Map<String, Object> result = (Map<String, Object>) JSONHelper.parse(HTTPHelper.post(url, body, header));


            System.out.println(body);

            if (result.get("msg").equals("登陆成功")) {
                System.out.println("执行了环绕通知的myAround方法");
                Map results = new HashMap();
                results.put("msg", "接口错误");
                results.put("SUCCESS", "false");
                return results;
            }


        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            Map results = new HashMap();
            results.put("msg", "异常");
            results.put("SUCCESS", "false");
            logger.info("同步通达部门异常==============》:" + e);
            return results;

        }
        return pjp.proceed();
    }

}
